package com.xunmall.base.logger.service;


import com.mongodb.MongoClient;
import com.xunmall.base.logger.BaseLogInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description: 日志保存到mongodb的service
 */
@ConditionalOnClass(MongoClient.class)
@Service
@Slf4j
public class LogService {
    @Autowired(required = false)
    private MongoTemplate mongoTemplate;

    @Async
    public void save(BaseLogInfo logInfo) {
        try {
            if (mongoTemplate == null) {
                log.debug("mongodb template is null!");
                return;
            }
            String collectionName = logInfo.getType() + "_" + LocalDate.now().toString().replace("-", "");
            mongoTemplate.insert(logInfo, collectionName);
            log.debug("save " + BaseLogInfo.class.getSimpleName() + " record success.");
        } catch (Exception e) {
            log.error("save " + BaseLogInfo.class.getSimpleName() + " error.", e);
        }
    }

}
